# coding: utf-8
import logging
import uuid
from datetime import datetime
from app.services.conversations import ConversationsService

# 常量定义
DEFAULT_DATA_CONF_ID = "1"
DEFAULT_STATUS = 1
DEFAULT_IS_DELETE = 0
SYSTEM_USER = "system_user"

# 日志配置
logger = logging.getLogger(__name__)


def get_or_create_conversation_id(prompt):
    """
    获取或创建会话ID
    如果创建会话失败，使用UUID作为备用
    
    Args:
        prompt: 提示信息
        
    Returns:
        str: 会话ID
    """
    try:
        # 创建会话对象，获取sjml_conversations表的id
        conversation_data = {
            'name': prompt,
            'user_id': SYSTEM_USER,
            'status': DEFAULT_STATUS,
            'start_at': datetime.now()
        }
        # 调用create_conversation方法创建会话并获取id
        created_conversation = ConversationsService.create_conversation(conversation_data)
        conversation_id = created_conversation.get('id')
        logger.info(f"成功创建会话，conversation_id: {conversation_id}")
        return conversation_id
    except Exception as e:
        # 如果创建会话失败，使用UUID作为备用
        conversation_id = str(uuid.uuid4())
        logger.error(f"创建会话失败，使用UUID作为备用: {str(e)}", exc_info=True)
        return conversation_id


def write_conversation_record(prompt, conversation_id):
    """
    写入会话记录到数据库
    
    Args:
        prompt: 提示信息
        conversation_id: 会话ID
    """
    try:
        data = {
            'conversation_id': conversation_id,
            'user_id': SYSTEM_USER,
            'data_conf_id': DEFAULT_DATA_CONF_ID,
            'step_title': prompt,
            'current_state': "1",  # 初始状态值
            'status': DEFAULT_STATUS,
            'is_delete': DEFAULT_IS_DELETE,
            'message_type': 'user'
        }
        ConversationsService.create_record(data)
        logger.info(f"数据已成功写入数据库，conversation_id: {conversation_id}")
    except Exception as e:
        logger.error(f"写入数据库失败: {str(e)}", exc_info=True)